<?php

namespace App\Controller\Admin;

use App\Controller\Example\AdminExample;
use App\Models\AdminModel;
use App\Models\Conn;
use Core\Common\Common;
use Core\Enums\ErrorEnum;
use Core\Result\Result;
use Core\Utils\Ip\Ipinit;

class Staff extends AdminModel
{
    /*后台登录
         * */
    public function adminLogin($data){
        $assemble = Common::assemble(new AdminExample(),$data);
        if($assemble->username == null){
            Result::error(ErrorEnum::USERNAMEISNULL);
        }
        if($assemble->password == null){
            Result::error(ErrorEnum::PASSWORDERROR);
        }
        $conn = new Conn();
        $adminInfo = self::getAdminInUsername($conn, $assemble);
        if(empty($adminInfo)){
            Result::error(ErrorEnum::USERNAMENULL);
        }
        if($adminInfo["status"] !=1){
            Result::error(ErrorEnum::DISABLELOGIN);
        }
        if($adminInfo["password"] != $assemble->password){
            Result::error(ErrorEnum::PASSWORDERROR);
        }
        $adminExample = new AdminExample();
        $adminExample->token = $adminInfo["token"];
        $adminExample->last_ip = new Ipinit();
        $adminExample->last_time = 'NOW()';
        $conn->shiwuStart();
        if(self::upAdminInside($conn,$adminExample) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::PRIVILEGEGRANTFAILED);
        }
        $conn->shiwuEnd();
        Result::success($adminInfo["token"]);
    }
    public function getAdminInfo($data){
        $assemble = Common::assemble(new AdminExample(), $data);
        $conn = new Conn();
        $adminInfo = self::getAdminInToken($conn, $assemble->token);
        if(empty($adminInfo)){
            Result::error(ErrorEnum::USERNAMENULL);
        }
        $adminId = $adminInfo["id"];
        $adminmenu_sql="SELECT `id`,`level`,`pid`,`path`, `component`, `redirect`, `name`, `title`, `icon` FROM `admin_menu` as a inner join `menu` as m on a.mid = m.id WHERE `aid` = $adminId order by `sort` desc";
        $adminmenu = $conn->readConn($adminmenu_sql,true);
        foreach ($adminmenu as $itme => $val){
            if(!empty($val["title"])){
                $adminmenu[$itme]["meta"]["title"] = $val["title"];
            }
            if(!empty($val["icon"])){
                $adminmenu[$itme]["meta"]["icon"] = $val["icon"];
            }
            unset($adminmenu[$itme]["title"]);
            unset($adminmenu[$itme]["icon"]);
        }
        $adminInfo["avatar"] = "http://cm.cmhm.xyz/web/adminLogo.gif?imageView2/1/w/80/h/80";
        $adminInfo["adminMenu"] = $adminmenu;
        Result::success($adminInfo);
    }
    /**
     * 查询所有权限
     */
    public function getAllPowerPermissions($conn){
        $powerSql="SELECT `id`,`level`,`pid`,`path`, `component`, `redirect`, `name`, `title`, `icon` FROM `menu`  WHERE `level` =1 and `id` <> 29 order by `id` asc";
        $readConn = $conn->readConn($powerSql, true);
        foreach ($readConn as $item => $value){
            $powerNextSql="SELECT `id`,`level`,`pid`,`path`, `component`, `redirect`, `name`, `title`, `icon` FROM `menu` WHERE `level` = 2 and `pid` = $value[id] order by `id` asc";
            $powerNextSqlComm = $conn->readConn($powerNextSql, true);
            if($readConn[$item]["title"] == null){
                $readConn[$item]["title"] = $powerNextSqlComm[0]["title"];
            }
            $readConn[$item]["children"] =  $powerNextSqlComm;
        }
        return $readConn;
    }
    /**
     * 通用当前管理查询权限
     */
    public function getPowerPermissions($conn,$aid){
        $powerSql="SELECT `id`,`level`,`pid`,`path`, `component`, `redirect`, `name`, `title`, `icon` FROM `admin_menu` as a inner join `menu` as m on a.mid = m.id WHERE `aid` = $aid and `level` = 1 order by `id` asc";
        $readConn = $conn->readConn($powerSql, true);
        foreach ($readConn as $item => $value){
            $powerNextSql="SELECT `id`,`level`,`pid`,`path`, `component`, `redirect`, `name`, `title`, `icon` FROM `admin_menu` as a inner join `menu` as m on a.mid = m.id WHERE `aid` = $aid and `level` = 2 and `pid` = $value[id] order by `id` asc";
            $powerNextSqlComm = $conn->readConn($powerNextSql, true);
            if($readConn[$item]["title"] == null){
                $readConn[$item]["title"] = $powerNextSqlComm[0]["title"];
            }
            $readConn[$item]["children"] =  $powerNextSqlComm;
        }
        return $readConn;
    }
    /**
     * 权限管理列表
     * entry token
     * return json
     * */
    public function power($data){
        $identical = Common::identical($data);
        $conn = new Conn();
        $adminSql="SELECT `id`, `username`, `level`, `time`, `last_time`, `last_ip`,`remarks` FROM `admin` WHERE `id` >1 and `status` >=0 order by id asc limit $identical->pageStart,$identical->limit";
        $readConn = $conn->readConn($adminSql, true);
        foreach ($readConn as $item => $value){
            $readConn[$item]["power"]  = $this->getPowerPermissions($conn,$value["id"]);
        }
        $adminCountSql="SELECT count(`id`) as count FROM `admin` WHERE `id` >1 and `status` >=0";
        $resData["count"] = $conn->readConn($adminCountSql)["count"];
        $resData["list"] = $readConn;
        Result::success($resData);
    }
    /**
     * 所有权限管理
     * entry token
     * return json
     * */
    public function allPower($data){
        $conn = new Conn();
        Result::success($this->getAllPowerPermissions($conn));
    }
    /**
     * 修改管理员权限管理
     * entry token,id,password,remarks,power,status
     * return json
     * */
    public function editPower($data){
        $power = $data["power"];
        $assemble = Common::assemble(new AdminExample(), $data);
        $conn = new Conn();
        $adminSql="SELECT `id`, `username`,`token` FROM `admin` WHERE `id`='$assemble->id'";
        $readConn = $conn->readConn($adminSql);
        if(empty($readConn)){
            Result::error("管理员不存在");
        }
        if($readConn["id"] == 1){
            Result::error("当前管理员不可编辑");
        }
        $adminExample = new AdminExample();
        $adminExample->token = $readConn["token"];
        $adminExample->password = $assemble->password;
        $adminExample->remarks = $assemble->remarks;
        $adminExample->status = $assemble->status;
        $adminExample->level = $assemble->level;
        $conn->shiwuStart();
        if(AdminModel::upAdminInside($conn,$adminExample) > 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::SUBMITFAILED);
        }
        if($power != null){
            $menuSql="SELECT `id` FROM `menu` WHERE `id` in($power) order by id ASC";
            $menuConn=$conn->readConn($menuSql,true);
            $delSql="DELETE FROM `admin_menu` WHERE `aid` = $assemble->id";
            $conn->executeConn($delSql);
            foreach ($menuConn as $item=>$val){
                $insertAdminMenuSql="INSERT INTO `admin_menu`(`aid`, `mid`, `time`) VALUES ($assemble->id,$val[id],NOW())";
                if($conn->executeConn($insertAdminMenuSql) !=1){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::SUBMITFAILED);
                }
            }
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 添加管理员
     * entry username,password,remarks,power,level
     * return json
     * */
    public function addAdmin($data){
        $assemble = Common::assemble(new AdminExample(), $data);
        $power = $data["power"];
        $conn = new Conn();
        if($assemble->username ==null || $assemble->password==null){
            Result::error(ErrorEnum::INCOMPLETEPARAMETERS);
        }
        //$assemble->level = 2;
        $assemble->token = md5($assemble->username);
        $sql="SELECT `id` FROM `admin` WHERE `username` = '".$assemble->username."' limit 1";
        $readConn = $conn->readConn($sql);
        if(!empty($readConn)){
            Result::error(ErrorEnum::YOUHAVEPREVIOUSLYREGISTEREDASIMILARACCOUNT);
        }
        if($assemble->bid == null){
            $assemble->bid = 0;
        }
        $insetSql="INSERT INTO `admin`(`token`, `username`, `password`, `level`, `bid`, `remarks`) VALUES ('".$assemble->token."','".$assemble->username."','".$assemble->password."','".$assemble->level."','".$assemble->bid."','".$assemble->remarks."')";
        $conn->shiwuStart();
        if($conn->executeConn($insetSql) !=1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ADDFAILED);
        }
        $admin_id = $conn->mysql_insert_id();
        if($power !=null){
            $powerlifter = explode(",", $power);
            foreach ($powerlifter as $value){
                $adminMenuInsetSql="INSERT INTO `admin_menu`(`aid`, `mid`) VALUES ($admin_id,$value)";
                if($conn->executeConn($adminMenuInsetSql) !=1){
                    $conn->shiwuRollback();
                    Result::error(ErrorEnum::ADDFAILED);
                }
            }
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 删除管理员
     * entry id,status
     * return json
     * */
    public function delAdmin($data){
        $assemble = Common::assemble(new AdminExample(), $data);
        $conn = new Conn();
        if($assemble->id ==null){
            Result::error(ErrorEnum::USERDOESNOTEXIST);
        }
        if($assemble->id ==1){
            Result::error(ErrorEnum::NOPERMISSIONTOSUBMIT);
        }
        $sql="SELECT `id` FROM `admin` WHERE `id` = '$assemble->id'";
        $readConn = $conn->readConn($sql);
        if(empty($readConn)){
            Result::error(ErrorEnum::USERDOESNOTEXIST);
        }
        $conn->shiwuStart();
        if(AdminModel::upAdminInside($conn,$assemble) != 1){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::DELETEFAILED);
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }

}